Public Class PicksController
    Inherits System.Web.Mvc.Controller

    Private picksRepo As New PickRepository()

    <Authorize()> _
    Function Index() As ActionResult
        Dim picks = picksRepo.FindAllPicksPerUser(User.Identity.Name).ToList
        Return View("Index", picks)
    End Function

    <Authorize()> _
    Function Edit(ByVal id As Integer) As ActionResult
        If Not IsUserStillAlive() Then
            ViewData("Msg") = "You are not eligible to make picks for Round " & id.ToString()
            Return View("NoPicks")
        Else
            Dim picks = picksRepo.FindUserPicksPerRound(User.Identity.Name, id)
            LoadViewData(id)
            Return View("Edit", picks)
        End If
    End Function

    Private Function IsUserStillAlive() As Boolean
        Dim picks = picksRepo.FindAllPicksPerUser(User.Identity.Name).ToList()

        For Each myPick In picks
            If myPick.Team IsNot Nothing Then
                Select Case myPick.BracketRound
                    Case 1
                        If myPick.Team.Round1Result IsNot Nothing AndAlso myPick.Team.Round1Result = 0 Then
                            Return False
                        End If
                    Case 2
                        If myPick.Team.Round2Result IsNot Nothing AndAlso myPick.Team.Round2Result = 0 Then
                            Return False
                        End If
                    Case 3
                        If myPick.Team.Round3Result IsNot Nothing AndAlso myPick.Team.Round3Result = 0 Then
                            Return False
                        End If
                    Case 4
                        If myPick.Team.Round4Result IsNot Nothing AndAlso myPick.Team.Round4Result = 0 Then
                            Return False
                        End If
                    Case 5
                        If myPick.Team.Round5Result IsNot Nothing AndAlso myPick.Team.Round5Result = 0 Then
                            Return False
                        End If
                    Case 6
                        If myPick.Team.Round6Result IsNot Nothing AndAlso myPick.Team.Round6Result = 0 Then
                            Return False
                        End If
                End Select
            End If
        Next

        Return True
    End Function

    Private Sub LoadViewData(Optional ByVal id As Integer = -1)
        Dim teamsRepo As New TeamRepository()
        ViewData("BasketballTeams") = teamsRepo.FindAllAliveTeams(curYear)
        ViewData("Deadline") = GetDeadlineTime(id)
        ViewData("Round") = id
    End Sub

    <AcceptVerbs(HttpVerbs.Post), Authorize()> _
    Function Edit(ByVal id As Integer, ByVal formValues As FormCollection) As ActionResult
        Try
            Dim picks = formValues("Pick").Split(",")
            Dim teams = formValues("Team").Split(",")

            If id > 1 Then
                'Check for existing picks
                Dim myPicks = picksRepo.FindAllPicksPerUser(User.Identity.Name)
                For i As Integer = 0 To picks.Count - 1
                    Dim tmpTeamId = teams(i)
                    For Each tmpPick In myPicks
                        If tmpPick.Team IsNot Nothing AndAlso tmpPick.Team.TeamId = tmpTeamId AndAlso tmpPick.BracketRound < id Then
                            'This team has already been chosen by this user in a previous round
                            ViewData("ErrorMsg") = String.Format("You have previously chosen {0}.  Please pick a different team.", tmpPick.Team.TeamName)
                            Return ReloadEditPicksPage(id)
                        End If
                    Next
                Next
            End If

            'Check for duplicates (only applicable within rounds 1 and 2)
            If id = 1 OrElse id = 2 Then
                Dim alRegions As New ArrayList
                Dim teamRepo As New TeamRepository()
                For i As Integer = 0 To picks.Count - 1
                    Dim tmpRegion = teamRepo.FindRegionForTeam(teams(i))
                    If alRegions.Contains(tmpRegion) Then
                        ViewData("ErrorMsg") = "Each team you select must be from a different region.  Try again!"
                        Return ReloadEditPicksPage(id)
                    Else
                        alRegions.Add(tmpRegion)
                    End If
                Next
            End If

            'All validation has passed, now save these choices to the database
            For i As Integer = 0 To picks.Count - 1
                If picks(i) IsNot Nothing AndAlso picks(i) <> "" Then
                    picksRepo.SavePickInfo(picks(i), teams(i))
                End If
            Next

            sysLog.Debug(String.Concat("Picks changed by ", User.Identity.Name))

            Return RedirectToAction("Index")
        Catch ex As Exception
            sysLog.Error("Editing picks --> " & ex.ToString())
            ViewData("ErrorMsg") = String.Concat("Error occurred: ", ex.Message)
            Return ReloadEditPicksPage(id)
        End Try
    End Function

    Private Function ReloadEditPicksPage(ByVal id As Integer) As ActionResult
        LoadViewData(id)
        Return View("Edit", picksRepo.FindUserPicksPerRound(User.Identity.Name, id))
    End Function

    Private Function GetDeadlineTime(ByVal round As Integer) As String
        Dim thisTime As DateTime = Nothing
        Select Case round
            Case 1
                thisTime = rd1Deadline
            Case 2
                thisTime = rd2Deadline
            Case 3
                thisTime = rd3Deadline
            Case 4
                thisTime = rd4Deadline
            Case 5
                thisTime = rd5Deadline
            Case 6
                thisTime = rd6Deadline
        End Select

        If Date.Compare(Date.Now, thisTime) > 0 Then
            Return String.Format("The deadline for picking this round was {0} {1}", thisTime.ToShortDateString(), thisTime.ToShortTimeString())
        Else
            Return ""
        End If
    End Function
End Class